package yxy.game.pm2.active.module.time;

import org.joda.time.DateTime;
import yxy.game.pm2.active.ActiveUtil;
import yxy.game.pm2.active.module.timemail.TimeMail;
import yxy.game.pm2.module.mail.MailHandle;

import java.util.ArrayList;
import java.util.Map;

public class ActiveTimeMailFutureHandle {

	// 时间控制===========================================================================

	public void update() {
		DateTime now = DateTime.now();
	
//		System.out.println("ActiveTimeMailFutureHandle " + now);
		try {
			if(TimeMail.lockTimeMail()) {
				ArrayList<String> tmcodes = new ArrayList<String>();
				
				Map<String, TimeMail> tmmap = TimeMail.all();
				for(TimeMail tm : tmmap.values()) {

					if(tm.isSend()) {
						int days = ActiveUtil.days(tm.getNeedsendtime(), now);
						if(days > 7) {
							tmcodes.add(tm.getTmcode());							
						}
						continue;
					}
					
					if(ActiveUtil.isSameDay(tm.getNeedsendtime(), now)) {
						tm.setSend(true);
						tm.set();
						new MailHandle().sendMail(tm.getPlayercode(), tm.getType(), tm.getTitle(), tm.getContent(), tm.getReason(), tm.getRewards());
					}
				}
				
				TimeMail.remove(tmcodes);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			TimeMail.unlockTimeMail();
		}

	}


// XXX TEST 短时测试
	static private boolean isOpen(DateTime time) {
		if (time == null) {
			return false;
		}

		int minute = time.getMinuteOfHour();
		return minute >= 5 && minute <= 59;// 每小时5分开始
	}


}
